<template>
  <div class="container mx-auto p-6">
    <h1 class="text-2xl font-semibold mb-4">短链接生成器</h1>

    <div class="mb-6">
      <div class="bg-white shadow-sm border rounded p-4 flex gap-4 items-start">
        <div class="text-purple-600 flex-shrink-0 mt-1">
          <!-- Info icon -->
          <svg xmlns="http://www.w3.org/2000/svg" class="h-7 w-7" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
            <path stroke-linecap="round" stroke-linejoin="round" d="M13 16h-1v-4h-1m1-4h.01M12 21.5a9.5 9.5 0 110-19 9.5 9.5 0 010 19z" />
          </svg>
        </div>
        <div class="prose">
          <h3 class="text-lg font-medium mb-1">功能说明</h3>
          <p>快速将长 URL 转换为短链接，便于分享。你可以为短链接设置过期时间（例如 1 天、7 天），或选择“永不过期”。如果选择自定义，请输入自定义天数。</p>
          <ul>
            <li>用途：社交分享、短期推广、短信/微信场景等。</li>
            <li>注意：设置较短的过期时间会让链接在过期后不可访问。</li>
            <li>后端会接收一个以秒为单位的过期时长（`expireSeconds`），值为 `null` 或 `0` 表示永不过期。</li>
          </ul>
        </div>
      </div>
    </div>

    <div class="mb-4">
      <label class="block text-sm font-medium mb-1">要缩短的 URL</label>
      <input v-model="inputUrl" placeholder="https://example.com/..." class="w-full border rounded p-2" />
    </div>

    <div class="mb-4">
      <label class="block text-sm font-medium mb-1">过期时间</label>
      <div class="flex items-center gap-3">
        <select v-model="expiry" class="border rounded p-2">
          <option v-for="opt in expiryOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
        </select>
        <div v-if="expiry === 'custom'" class="flex items-center gap-2">
          <input type="number" v-model.number="customDays" min="1" max="3650" class="w-28 border rounded p-2" />
          <span class="text-sm">天（1-3650）</span>
        </div>
      </div>
      <div class="text-xs text-gray-500 mt-2">当前选择：{{ expiryText }}</div>
    </div>

    <div class="flex items-center gap-3 mb-4">
      <button @click="createShort" class="bg-purple-600 text-white px-4 py-2 rounded inline-flex items-center gap-2">
        <!-- Link icon -->
        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
          <path stroke-linecap="round" stroke-linejoin="round" d="M13.828 10.172a4 4 0 010 5.656l-1.414 1.414a4 4 0 01-5.656-5.656l1.414-1.414M10.586 13.414l1.414-1.414" />
        </svg>
        生成短链接
      </button>
      <button @click="clear" class="border px-3 py-2 rounded">清空</button>
    </div>

    <div v-if="error" class="text-red-600 mb-2">{{ error }}</div>

    <div v-if="result" class="bg-gray-50 border p-3 rounded">
      <div class="mb-2">生成的短链接：</div>
      <div class="flex items-center">
        <input readonly :value="result.shortUrl" class="flex-1 border p-2 rounded mr-2" />
        <button @click="copy" class="bg-indigo-600 text-white px-3 py-2 rounded">复制链接</button>
      </div>
      <div class="mt-3 text-sm text-gray-600">过期时间：{{ result.expireAt ? new Date(result.expireAt).toLocaleString() : '永不过期' }}</div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

const inputUrl = ref('')
const result = ref(null)
const error = ref('')

const expiryOptions = [
  { label: '永不过期', value: 0 },
  { label: '1 小时', value: 3600 },
  { label: '1 天', value: 86400 },
  { label: '7 天', value: 604800 },
  { label: '30 天', value: 2592000 },
  { label: '自定义（天）', value: 'custom' }
]

const expiry = ref(0)
const customDays = ref(7)

const expirySeconds = computed(() => {
  if (expiry.value === 'custom') {
    const days = Number(customDays.value) || 0
    return days > 0 ? days * 86400 : 0
  }
  return Number(expiry.value) || 0
})

const expiryText = computed(() => {
  if (expiry.value === 'custom') return `${customDays.value} 天（自定义）`
  if (!expirySeconds.value) return '永不过期'
  if (expirySeconds.value < 3600) return `${Math.floor(expirySeconds.value / 60)} 分钟`
  if (expirySeconds.value < 86400) return `${Math.floor(expirySeconds.value / 3600)} 小时`
  return `${Math.floor(expirySeconds.value / 86400)} 天`
})

async function createShort() {
  error.value = ''
  result.value = null
  if (!inputUrl.value) {
    error.value = '请输入要缩短的 URL'
    return
  }
  if (expiry.value === 'custom') {
    const d = Number(customDays.value)
    if (!Number.isInteger(d) || d <= 0) {
      error.value = '自定义天数请输入正整数'
      return
    }
    if (d > 3650) {
      error.value = '自定义天数不能超过 3650 天'
      return
    }
  }

  try {
    const payload = { url: inputUrl.value }
    const secs = expirySeconds.value
    // 如果为 0 则后端可认为是永不过期；也可以发送 null
    payload.expireSeconds = secs > 0 ? secs : null

    const res = await $fetch('/api/shortlink', { method: 'POST', body: payload })
    result.value = res
  } catch (e) {
    error.value = e?.statusMessage || e?.message || '创建失败'
  }
}

function copy() {
  if (!result.value) return
  navigator.clipboard.writeText(result.value.shortUrl)
}

function clear() {
  inputUrl.value = ''
  result.value = null
  error.value = ''
  expiry.value = 0
  customDays.value = 7
}
</script>

<style scoped>
.container { max-width: 800px }
</style>
